<?php
namespace addons\cloudstorage\driver;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\File;
use think\Exception;

class Qiniu extends Driver
{
    protected $auth;
    protected $uploadManager;
    
    public function __construct($config, $domain = '')
    {
        parent::__construct($config, $domain);
        
        try {
            $this->auth = new Auth(
                $this->config['accessKey'],
                $this->config['secretKey']
            );
            $this->uploadManager = new UploadManager();
        } catch (Exception $e) {
            throw new Exception('七牛云初始化失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 上传文件
     */
    public function upload(File $file, $path = '')
    {
        try {
            $object = $this->getObjectPath($file, $path);
            $filePath = $file->getRealPath();
            
            // 生成上传Token
            $token = $this->auth->uploadToken($this->config['bucket']);
            
            // 执行上传
            list($ret, $err) = $this->uploadManager->putFile(
                $token,
                $object,
                $filePath
            );
            
            if ($err !== null) {
                return [
                    'status' => false,
                    'msg'    => '上传失败: ' . $err->message()
                ];
            }
            
            return [
                'status' => true,
                'path'   => $object,
                'url'    => $this->getUrl($object)
            ];
        } catch (Exception $e) {
            return [
                'status' => false,
                'msg'    => '上传失败: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        try {
            $config = new \Qiniu\Config();
            $bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
            list($err, $resp) = $bucketManager->delete($this->config['bucket'], $filePath);
            
            return $err === null;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取对象存储路径
     */
    protected function getObjectPath(File $file, $path = '')
    {
        $ext = $file->getExtension();
        $filename = md5(microtime(true) . uniqid()) . '.' . $ext;
        
        if ($path) {
            $path = rtrim($path, '/') . '/';
        }
        
        // 按日期组织路径
        $datePath = date('Ymd') . '/';
        
        return $path . $datePath . $filename;
    }
}
?>
